package vip.ola.pay.channel.daifuchannel.laojiudaifu;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.ola.core.common.util.IPUtility;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.AgentpayPassageAccount;
import vip.ola.core.entity.TransOrder;
import vip.ola.pay.ctrl.common.BaseController;
import vip.ola.pay.mq.BaseNotify4MchTrans;
import vip.ola.pay.service.RpcCommonService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import static vip.ola.core.common.constant.PayConstant.TRANS_STATUS_COMPLETE;
import static vip.ola.core.common.constant.PayConstant.TRANS_STATUS_SUCCESS;

@RequestMapping("/api/ljpay")
@Controller
public class LjpayTransController extends BaseController {

    private static final MyLog _log = MyLog.getLog(LjpayTransController.class);

    @Autowired
    private RpcCommonService rpcCommonService;

    @Autowired
    public BaseNotify4MchTrans baseNotify4MchTrans;

    @PostMapping("/notify")
    @ResponseBody
    public String notify(@RequestBody JSONObject object, HttpServletRequest request){
        _log.info("接收LjpayTransController回调：" + object);
        // 判断请求IP是否允许+"："
        String clintIp = IPUtility.getClientIp(request);
        _log.info("请求ip为：" + clintIp);
        boolean isAllow = PayUtil.ipAllow(clintIp, "20.78.39.213,34.81.77.15,52.197.237.150", "");
        if (!isAllow) {
            _log.info( "IP[" + clintIp + "]不允许访问");
            return "ip fail";
        }
        String transOrderId = object.getString("OrderNo");
        TransOrder payOrder = rpcCommonService.rpcTransOrderService.findByTransOrderId(transOrderId);
        BigDecimal orderMoney = new BigDecimal(object.getString("Amount")).multiply(BigDecimal.valueOf(100));
        if (orderMoney.longValue() != payOrder.getAmount()){
            return "money fail";
        }
        if(payOrder == null){
            return "order not exist!";
        }
        if (payOrder.getStatus() == TRANS_STATUS_SUCCESS || payOrder.getStatus() == TRANS_STATUS_COMPLETE) {
            return "ok";
        }
        AgentpayPassageAccount payPassageAccount = rpcCommonService.rpcAgentpayPassageAccountService.findById(payOrder.getPassageAccountId());
        if(payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())){
            return "fail";
        }
        JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
        String retSign = object.getString("Sign");
        String privateKey = accountParams.getString("privateKey");
//        Map<String,String> signMap = new HashMap<>();
//        signMap.put("Timestamp",object.getString("Timestamp"));
//        signMap.put("AccessKey",object.getString("AccessKey"));
//        signMap.put("Status",object.getString("Status"));
//        signMap.put("OrderNo",object.getString("OrderNo"));
//        signMap.put("Amount",object.getString("Amount"));
//        if (StringUtils.isNotEmpty(object.getString("Ext"))){
//            signMap.put("Ext",object.getString("Ext"));
//        }
//        if (StringUtils.isNotEmpty(object.getString("Comment"))){
//            signMap.put("Comment",object.getString("Comment"));
//        }
        object.remove("Sign");
        String sign =LjpayTransService.getSign(object, privateKey);
        _log.info("加签信息：map-{},sign->{}", object, sign );
        try{
            if (sign.equals(retSign)){
                if (object.getInteger("Status").intValue() == 4){
                    //查询代付订单状态
                    String queryUrl = accountParams.getString("queryUrl");
                    Map<String, Object> obj = new HashMap<>();
                    Long timestamp = System.currentTimeMillis()/1000;
                    obj.put("Timestamp", timestamp);
                    obj.put("OrderNo", transOrderId);
                    obj.put("AccessKey", payPassageAccount.getPassageMchId());
                    String querySign = LjpayTransService.getSign(obj,privateKey);
                    obj.put("Sign", querySign);
                    _log.info("查询请求url={}，json->{}",queryUrl,JSONObject.toJSONString(obj));
                    String respData = LjpayTransService.call(queryUrl,obj);
                    _log.info("查询结束respData->{}",respData);
                    if (StringUtils.isNotEmpty(respData)) {
                        JSONObject jsonObject = JSONObject.parseObject(respData);
                        String code = jsonObject.getString("Code");
                        if ("0".equals(code)){
                            String data = jsonObject.getString("data");
                            if (StringUtils.isNotEmpty(data)){
                                int statss = JSONObject.parseObject(respData).getInteger("Status");
                                if (statss ==4){
                                    int result =  rpcCommonService.rpcTransOrderService.updateStatus4Success(transOrderId, "");
                                    _log.info("更新订单状态为支付成功: result={}", result);
                                    if(result == 1){
                                        // 通知业务系统
                                        baseNotify4MchTrans.doNotify(payOrder, true);
                                        return "ok";
                                    }
                                }
                            }
                        }
                    }
                }else {
                    if (object.getInteger("Status").intValue() == 16){
                        int result =   rpcCommonService.rpcTransOrderService.updateStatus4Fail(transOrderId, "16","撤单失败");
                        if(result == 1){
                            // 通知业务系统
                            baseNotify4MchTrans.doNotify(payOrder, true);
                            return "ok";
                        }
                    }else {
                        int status = object.getInteger("Status");
                        int result = rpcCommonService.rpcTransOrderService.updateStatus4Fail(transOrderId, String.valueOf(status),"失败");
                        if(result == 1){
                            // 通知业务系统
                            baseNotify4MchTrans.doNotify(payOrder, true);
                            return "ok";
                        }
                    }
                }

            }else {
                _log.info("sign error");
                return "sign fail!";
            }
        }catch (Exception e){
            e.printStackTrace();
            _log.info("sign error,e->{}",e.getMessage());
        }
        return "fail!";
    }

    private String getSign(Map<String,String>object, String privateKey) {
        SortedMap<String,String> map = new TreeMap<>(object);
        map.remove("sign");
        // 生成签名
        StringBuffer paramstr = new StringBuffer();
        for (String pkey : map.keySet()) {
            String pvalue = map.get(pkey);
            if (pvalue != null && pvalue != "") {
                paramstr.append(pkey + "=" + pvalue + "&");
            }
        }
        String paramsrc = paramstr.substring(0, paramstr.length() - 1);
        StringBuffer strbuff = new StringBuffer();
        strbuff.append(paramsrc +  privateKey);
        String sign = null;
        try {
            sign = PayDigestUtil.md5(strbuff.toString(), "UTF-8");
            _log.info("签名:" + sign);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sign;
    }


}
